package com.guli.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guli.base.exception.GuliException;
import com.guli.edu.client.VodClient;
import com.guli.edu.entity.Video;
import com.guli.edu.entity.form.VideoForm;
import com.guli.edu.mapper.VideoMapper;
import com.guli.edu.service.VideoService;
import com.guli.utils.R;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 课程视频 服务实现类
 * </p>
 *
 * @author ZhaoZhenyu
 * @since 2022-09-27
 */

@Service
public class VideoServiceImpl extends ServiceImpl<VideoMapper, Video> implements VideoService {

    @Autowired
    private VodClient vodClient;

    @Autowired
    private VideoMapper videoMapper;

    @Override
    public int getCount(String chapterId) {
        return baseMapper.selectCount(new QueryWrapper<Video>().eq("chapter_id", chapterId));
    }

    @Override
    public void saveVideo(VideoForm videoForm) {
        Video video = new Video();
        BeanUtils.copyProperties(videoForm,video);
        int count = baseMapper.insert(video);
        if (count == 0) throw new GuliException(20001, "添加课时失败");
    }

    @Override
    public VideoForm getVideoFormById(String id) {
        Video video = baseMapper.selectById(id);
        if (video == null) throw new GuliException(20001, "数据不存在");
        VideoForm videoForm = new VideoForm();
        BeanUtils.copyProperties(video,videoForm);
        return videoForm;
    }

    @Override
    public void updateVideoFormById(VideoForm videoForm) {
        Video video = new Video();
        BeanUtils.copyProperties(videoForm,video);
        int count = baseMapper.updateById(video);
        if (count == 0)  throw new GuliException(20001, "课时更新失败");
    }

    @Override
    public int DeleteChapterBatchByChapterId(String chapterId) {
        // 根据chapterId找出所有的小节和视频
        QueryWrapper<Video> wrapper = new QueryWrapper<>();
        wrapper.eq("chapter_id", chapterId);
        // 根据chapterId查videoSourceId
        List<String> videoIdList = videoMapper.selectVideoIdByChapterId(chapterId);
        // 远程调用删除
        R r = vodClient.deleteBatch(videoIdList);
        if (r.getCode() == 20001) throw new GuliException(20001, "删除小结视频失败");
        int count = baseMapper.delete(wrapper);
        return count;
    }

}
